package com.jt.service;

import com.jt.vo.ImageVO;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService{

    //定义文件的根目录
    private String rootDir = "D:/project3/images";
    //定义图片服务器网址
    private String rootURl = "http://image.jt.com";

    /**
     * 思路:
     *  1.校验文件是否为图片  校验图片类型
     *  2.防止文件为恶意程序  木马.exe.jpg
     *  3.分目录存储         按照时间维度划分
     *  4.防止文件重名       UUID
     */
    @Override
    public ImageVO upload(MultipartFile file) {
        //1.获取图片名称,全部转化为小写  abc.jpg
        String fileName = file.getOriginalFilename().toLowerCase();
        if(!fileName.matches("^.+\\.(jpg|png|gif)$")){
            return null;
        }

        //2.通过校验宽度和高度判断是否为图片 bufferedImage图片包装对象
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if(width == 0 || height == 0){
                return null;
            }

            //3.实现分目录的存储
            String datePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            //D:/project3/images/2025/11/11/
            String fileDir = rootDir + datePath;
            File dirFile = new File(fileDir);
            if(!dirFile.exists()){
                dirFile.mkdirs();
            }

            //4.动态生成UUID
            String UUID = java.util.UUID.randomUUID().toString();
            int index = fileName.lastIndexOf(".");
            String fileType = fileName.substring(index);
            fileName = UUID+fileType;

            //5.实现文件上传  准备文件的全路径
            String path = fileDir + fileName;
            file.transferTo(new File(path));

            //6.准备ImageVO数据返回 /2021/11/11/uuid.jpg
            //封装VO对象对象
            String virtualPath = datePath + fileName;
            //String urlPath = "https://img14.360buyimg.com/n0/jfs/t1/172855/37/23003/136174/61b053d3Eb780b286/448d26aa148e6ea7.jpg";
            //按照要求封装图片网络地址
            //http://image.jt.com/2021/11/11/uuid.jpg
            String urlPath =  rootURl + virtualPath;
            System.out.println(urlPath);
            ImageVO imageVO = new ImageVO(virtualPath,urlPath, fileName);
            return imageVO;
        } catch (IOException e) {
            //一般条件下为了不影响代码结构,将检查异常,转化为运行时异常
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    //删除文件  需要文件全路径
    @Override
    public void deleteFile(String virtualPath) {
        String localPath = rootDir + virtualPath;
        File file = new File(localPath);
        if(file.exists()){ //如果文件存在,则删除
            file.delete();
        }
    }
}
